<script setup lang="ts">
import { Units } from "@scvzerng/esi-163";
import { BigDecimal } from "@chulei-ui/utils";
import { asyncComputed } from "@vueuse/core";
import { esi } from "../../src/repositories";
import type { DogmaAttribute } from "@scvzerng/esi-163";
const props = defineProps<{ attributes?: (Pick<DogmaAttribute, "attribute_id"> & { value: number })[] }>();

const value = defineModel<boolean>();
type TypeAttribute = { attribute_id: number; value: number; attribute: DogmaAttribute };
const typeAttributes = asyncComputed(async () => {
  const attrs: TypeAttribute[] = [];
  for (const attribute of props.attributes ?? []) {
    const attributeMeta = await esi.dogma.attribute(attribute.attribute_id);
    if (attributeMeta?.published) {
      attrs.push({
        ...attribute,
        attribute: attributeMeta,
      });
    }
  }
  value.value = attrs.length > 0;
  return attrs;
});

const sizeText: Record<number, string> = {
  1: "小型",
  2: "中型",
  3: "大型",
  4: "旗舰型",
};

const unitValueConverter: Record<string, (value: number | string) => number | string> = {
  "%": (value: number | string) => {
    if (Math.abs(value as number) > 1) return value;
    return BigDecimal.form(1)?.subtract(value).multiply(100).toFixed(2)?.toNumber()!;
  },
  s: (value: number | string) => {
    return BigDecimal.form(value)?.divide(1000).toFixed(2)?.toNumber()!;
  },
  "1=True 0=False": (value: number | string) => {
    return value ? "是" : "否";
  },
  "1=small 2=medium 3=l": (value: number | string) => {
    return sizeText[value as number];
  },
  attributeID: () => {
    return "";
  },
};

const getUnitValue = (value: string | number, uintId: number) => {
  return unitValueConverter[getUnit(uintId)!]?.(value) ?? value;
};

const unitText: Record<string, string> = {
  "m/sec": "米/秒",
  attributeID: "",
  typeID: "",
  groupID: "",
  "1=True 0=False": "",
  points: "点",
};
const getUnit = (unitId?: number) => {
  if (!unitId) return;
  const unit = Units[unitId];
  if (unit) {
    const valueConverter = unitValueConverter[unit];
    if (valueConverter) {
      return valueConverter(unit);
    }
    return unitText[unit?.displayName] ?? unit?.displayName;
  }
  return null;
};
</script>

<template>
  <el-descriptions :column="1" border>
    <el-descriptions-item
      v-for="attribute in typeAttributes"
      :key="attribute.attribute.display_name"
      :label="attribute.attribute.display_name"
    >
      {{ getUnitValue(attribute.value ?? attribute.attribute.default_value, attribute.attribute.unit_id!) }}
      {{ getUnit(attribute.attribute.unit_id) }}
    </el-descriptions-item>
  </el-descriptions>
</template>

<style scoped lang="scss"></style>
